﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WMSABL;
using ElectronicWMSA.Comm.Forms.Message;
using SYDZ.WMS.DBUtility;
using System.Threading;

namespace ElectronicWMSA.Warehouse
{
    public partial class List_StockBackFrm : Form
    {
        #region
        private string strWhere1 = "";
        PublicDataSet bll_PublicDataSet = new PublicDataSet();
        public List_StockBackFrm()
        {
            InitializeComponent();
        }

        private void List_StockBackFrm_Load(object sender, EventArgs e)
        {
            pageControl1.PageCurrent = 1;
            pageControl1.PageSize = 50;
        }
        #endregion

        #region
        public void DBindCombox()
        {
            if (true)
            {
                //DataSet ds = new DataSet();
                //ds = bll_PublicDataSet.GetDataSet("PD_Warehouse", "");
                //DataTable dt = ds.Tables[0];
                //DataRow dr = dt.NewRow();
                //dr["NID"] = "0";
                //dr["WarehouseName"] = "--请选择--";
                //dt.Rows.InsertAt(dr, 0);
                //this.comboBoxWareHouse.DataSource = dt;
                //this.comboBoxWareHouse.ValueMember = "NID";
                //this.comboBoxWareHouse.DisplayMember = "WarehouseName";
            }
        }
        #endregion

        #region 数据
        private int DBindData1()
        {
            ElectronicWMSA.Comm.Forms.MsControls.PageData pageData = new ElectronicWMSA.Comm.Forms.MsControls.PageData();
            pageData.TableName = "T_StockBackBack";
            pageData.PrimaryKey = "NID";
            pageData.OrderStr = "NID desc";
            pageData.PageIndex = this.pageControl1.PageCurrent;
            pageData.PageSize = this.pageControl1.PageSize;
            pageData.QueryCondition = strWhere1;
            pageData.QueryFieldName = "*";
            WaitingBoxFrm wf = new WaitingBoxFrm((obj, args) => { Thread.Sleep(500); pageData.QueryDataTable(); }, 500); wf.ShowDialog(this);
            pageControl1.bindingSource.DataSource = pageData.dsInfo.Tables[0]; 
            pageControl1.bindingNavigator.BindingSource = pageControl1.bindingSource;
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = this.pageControl1.bindingSource;
            dataGridView1.ClearSelection();
            dataGridView1.CurrentCell = null;
            return pageData.TotalCount;
        }
        private int pageControl1_EventPaging(ElectronicWMSA.Comm.Forms.MsControls.EventPagingArg e)
        {
            return DBindData1();
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
        }
        #endregion

        private void btnUserSearch_Click(object sender, EventArgs e)
        {
            // if (!SystemVariable.VaildationPermission("查询")) return;
            strWhere1 = " 1=1 ";
            if (!string.IsNullOrEmpty(txt_PO.Text))
            {
                this.strWhere1 += "  AND  PutList_NO like '%" + txt_PO.Text.Trim() + "%'";
            }

            if (this.txt_Leixing.Text.Trim() != "--请选择--" && this.txt_Leixing.Text.Trim() != "")
                this.strWhere1 += " AND bk03 like '%" + this.txt_Leixing.Text.Trim() + "%' ";

            if (this.txt_Machine.Text.Trim() != "--请选择--" && this.txt_Machine.Text.Trim() != "")
                this.strWhere1 += " AND Product_Model  like  '%" + this.txt_Machine.Text.Trim() + "' ";
            if (!string.IsNullOrEmpty(txt_SN.Text))
            {
                this.strWhere1 += "  AND  Serial_Number like '" + txt_SN.Text.Trim() + "%'";
            }
            if (dtpTimeStart.Checked)
            {
                this.strWhere1 += "  AND  convert(varchar(10),Update_Time,120) >= '" + dtpTimeStart.Text.Trim() + "'";

            }
            if (dtpTimeEnd.Checked)
            {
                this.strWhere1 += "  AND  convert(varchar(10),Update_Time,120) <= '" + dtpTimeEnd.Text.Trim() + "'";
            }
            this.pageControl1.Bind();
        }

        #region  Close
        private void linkLabelClose_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPages();
        }

        private void linkLabellinkLabelCloseAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseAllTabPages();
        }

        private void linkLabelCloseElse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Main._Main.CloseTabPageElse();
        }
        #endregion

        private void btnReport_Click(object sender, EventArgs e)
        {
            MessageClass.warning("预览出错！");
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            bool flg = BackReturn();
            List<string> list = new List<string>();
            if (flg)
            {
                // 禁用此功能（后续需改善盘点功能再考虑此方式）

                //if (MessageBox.Show("再次确认是否备份？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                //{
                //    list.Add("   truncate table T_StockPrepare; ");
                //    list.Add("   truncate table T_TemRuStock ;");
                //    list.Add("   delete   T_Stock where PickList_NO  is  null   ");
                //    int rows = DbHelperSQL.ExecuteSqlTran(list);
                //    if (rows != 0)
                //    {
                //        MessageBox.Show("操作成功" + rows);
                //    }
                //    else
                //    {
                //        MessageBox.Show("操作失败");
                //    }
                //}
            }
            else
            {
                MessageBox.Show("操作失败");
            }

        }

        /// <summary>
        /// 查询datatable
        /// </summary>
        /// <param name="Where"></param>
        private bool BackReturn()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("insert  into  T_StockBackBack ");
            sb.Append(" select [PutList_NO]=[PutList_NO]");
            sb.Append("  ,[OutList_NO]=[OutList_NO]");
            sb.Append("  ,[PickList_NO]=[PickList_NO]");
            sb.Append("  ,[BanHao]=[BanHao]");
            sb.Append("  ,[List_NOType]=[List_NOType]");
            sb.Append("  ,[Posiont1]=[Posiont1]");
            sb.Append("  ,[Posiont2]=[Posiont2]");
            sb.Append("  ,[Product_Model]=[Product_Model]");
            sb.Append("  ,[Serial_Number]=[Serial_Number]");
            sb.Append("  ,[Product_Weight]=[Product_Weight]");
            sb.Append("   ,[Create_Time]=[Create_Time]");
            sb.Append("  ,[Update_Time]=[Update_Time]");
            sb.Append("   ,[Update_UserID]=[Update_UserID]");
            sb.Append("  ,[RuKu_Time1]=[RuKu_Time1]");
            sb.Append(" ,[RuKu_Time2]=[RuKu_Time2]");
            sb.Append("    ,[BK01]=[BK01]");
            sb.Append("  ,[BK02]=[BK02]");
            sb.Append("    ,[BK03]=[BK03]");
            sb.Append("  ,[BK04]=[BK04]");
            sb.Append("   ,[BK05]=[BK05]");
            sb.Append("  ,[BK06]=[BK06]");
            sb.Append("   ,[BK07]=[BK07]");
            sb.Append("  ,[BK08]=[BK08]");
            sb.Append("  ,[BK09]=[BK09]");
            sb.Append(" ,[BK10]=[BK10]");
            sb.Append(" ,[BK11]=[BK11]");
            sb.Append(" ,[BK12]=[BK12]");
            sb.Append(" ,[BK13]=[BK13]");
            sb.Append("  ,[BK14]=[BK14]");
            sb.Append("  ,[BK15]=[BK15]");
            sb.Append("  ,[BK16]=[BK16]");
            sb.Append(",[BK17]=[BK17]");
            sb.Append("   ,[BK18]=[BK18]");
            sb.Append(" ,[BK19]=[BK19]");
            sb.Append("   ,[BK20]=GETDATE() ");

            sb.Append(" FROM [dbo].[T_Stock] where PickList_NO  is  null ");
            List<string> list = new List<string>();
            list.Add(sb.ToString());
            int rows = DbHelperSQL.ExecuteSqlTran(list);
            if (rows != 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 将DataTable转换成CSV文件
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="filePath">文件路径</param>
        public static void SaveCsv(DataTable dt)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "csv(*.csv)|*.csv";
            saveFileDialog1.FilterIndex = 0;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.CreatePrompt = true;
            saveFileDialog1.Title = "导出csv文件到 ";

            saveFileDialog1.ShowDialog();

            string sSaveFullPath = saveFileDialog1.FileName;//导出全路径
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                fs = new FileStream(sSaveFullPath, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.Default);
                var data = string.Empty;
                //写出列名称
                //for (var i = 0; i < dt.Columns.Count; i++)
                //{
                //    data += dt.Columns[i].ColumnName;
                //    if (i < dt.Columns.Count - 1)
                //    {
                //        data += ",";
                //    }
                //}
                sw.WriteLine(data);
                //写出各行数据
                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    data = string.Empty;
                    for (var j = 0; j < dt.Columns.Count; j++)
                    {
                        data += dt.Rows[i][j].ToString();
                        if (j < dt.Columns.Count - 1)
                        {
                            data += ",";
                        }
                    }
                    sw.WriteLine(data);
                }
            }
            catch (IOException ex)
            {
                throw new IOException(ex.Message, ex);
            }
            finally
            {
                if (sw != null) sw.Close();
                if (fs != null) fs.Close();
            }
        }
    }
}
